# 录音机模块

import os
import pyaudio
import wave


class MyRecorder:

    def __init__(self, seconds=5, output_file_name='recorded_audio.wav'):
        self.CHUNK = 1024
        self.FORMAT = pyaudio.paInt16
        self.CHANNELS = 1
        self.RATE = 16000
        self.RECORD_SECONDS = seconds
        self.output_file_name = output_file_name

    def start_recording(self):
        p = pyaudio.PyAudio()

        stream = p.open(format=self.FORMAT,
                        channels=self.CHANNELS,
                        rate=self.RATE,
                        input=True,
                        frames_per_buffer=self.CHUNK)

        print("开始录音，主人请讲......")

        frames = []

        for i in range(0, int(self.RATE / self.CHUNK * self.RECORD_SECONDS)):
            data = stream.read(self.CHUNK)
            frames.append(data)

        print("录音结束，我已听到！")

        stream.stop_stream()
        stream.close()
        p.terminate()

        wf = wave.open(self.output_file_name, 'wb')
        wf.setnchannels(self.CHANNELS)
        wf.setsampwidth(p.get_sample_size(self.FORMAT))
        wf.setframerate(self.RATE)
        wf.writeframes(b''.join(frames))
        wf.close()

    def get_recorded_file_path(self):
        output_file_path = os.path.join('.', self.output_file_name)
        return output_file_path


if __name__ == '__main__':
    my_recorder = MyRecorder()
    my_recorder.start_recording()
